//
//  HomeViewController.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "HomeViewController.h"

#import "FolderViewController.h"
#import "OthersViewController.h"

#import "FormattingUtilities.h"
#import "NSString+GSSAdditions.h"
#import "GSSCommunicator.h"

@implementation HomeViewController

@synthesize footerAnnouncementsLabel;

//MARK: -

- (id)init {
    if (self = [super initWithNibName:@"HomeViewController" bundle:nil]) {
        object = [[[GSSCommunicator defaultCommunicator] home] retain];
    }
    return self;
}

- (void)dealloc {
    [footerAnnouncementsLabel release];
    [super dealloc];
}

- (void)showLoggedOutMode {
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
                                               initWithTitle:LocalizedString(@"Login")
                                                       style:UIBarButtonItemStyleBordered
                                                      target:self
                                                      action:@selector(login)] autorelease];
    [self reloadData];
    [self reloadToolbar];
    self.footerTopLabel.text = nil;
    self.footerBottomLabel.text = nil;
}    

- (void)reloadLoginButton {
    GSSCommunicator *communicator = [GSSCommunicator defaultCommunicator];
    if (!communicator.username || !communicator.token) {
        [self showLoggedOutMode];
    } else {
        UIBarButtonItem *logoutButton = [[UIBarButtonItem alloc] initWithTitle:LocalizedString(@"Logout")
                                                                         style:UIBarButtonItemStyleBordered
                                                                        target:self
                                                                        action:@selector(logout)];
        self.navigationItem.rightBarButtonItem = logoutButton;
        [logoutButton release];
    }
}


//MARK: -
//MARK: UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = LocalizedString(@"Pithos");
    
    UIBarButtonItem *aboutButton = [[UIBarButtonItem alloc] initWithTitle:LocalizedString(@"About")
                                                                    style:UIBarButtonItemStyleBordered
                                                                   target:self
                                                                   action:@selector(about)];
    self.navigationItem.leftBarButtonItem = aboutButton;
    [aboutButton release];
    
    [self reloadLoginButton];
}

//MARK: -
//MARK: UITableViewDataSource

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
    if (aTableView != self.tableView)
        return [super tableView:aTableView numberOfRowsInSection:section];

    return [object.children count];    
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (aTableView != self.tableView)
        return [super tableView:aTableView cellForRowAtIndexPath:indexPath];
    
    static NSString *CellIdentifier = @"HomeViewCell";
    
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc]
                 initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
        cell.textLabel.lineBreakMode = UILineBreakModeMiddleTruncation;
    }
    
    GSSObject *child = [object.children objectAtIndex:indexPath.row];    
    cell.textLabel.text = child.name;
    cell.imageView.image = child.icon;
    
    if (child.type == GSSObjectTypeRoot && child.isStale)
        [[GSSCommunicator defaultCommunicator] prefetchObject:child];

    return cell;
}


//MARK: -
//MARK: UITableViewDelegate

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (aTableView != self.tableView)
        return [super tableView:aTableView didSelectRowAtIndexPath:indexPath];

    FolderViewController *folderViewController = nil;
    GSSObject *child = [object.children objectAtIndex:indexPath.row];
    
    switch (child.type) {
        case GSSObjectTypeRoot:
        case GSSObjectTypeFolder:
            folderViewController = [[FolderViewController alloc] initWithGSSObject:child];
            break;
        
        case GSSObjectTypeShared:
            folderViewController = [[FolderViewController alloc] initWithGSSObject:child];
            folderViewController.showsAddButton = NO;
            break;
        
        case GSSObjectTypeOthers:
            folderViewController = [[OthersViewController alloc] initWithGSSObject:child];
            break;
            
        case GSSObjectTypeTrash:
            folderViewController = [[FolderViewController alloc] initWithGSSObject:child];
            folderViewController.showsAddButton = NO;
            folderViewController.showsDeleted = YES;
            break;
        
        default:
            NSLog(@"Unknown object type: %d", child.type);
            return;
    }
    
    [self.navigationController pushViewController:folderViewController animated:YES];
    [folderViewController release];
}


//MARK: -
//MARK: AboutViewController delegate

- (void)aboutEnded {    
	[self dismissModalViewControllerAnimated:YES];
}


//MARK: -
//MARK: Button Actions

- (void)about {    
	AboutViewController *aboutViewController = [[AboutViewController alloc] init];
	aboutViewController.delegate = self;
	aboutViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:aboutViewController animated:YES];
	[aboutViewController release];
}

- (void)login {
    [self authenticate];
}

- (void)logout {
    [[GSSCommunicator defaultCommunicator] logout];
    [self showLoggedOutMode];
}


//MARK: -

- (void)reload {
    if (!object) {
        object = [[[GSSCommunicator defaultCommunicator] home] retain];
        [[GSSCommunicator defaultCommunicator] updateMetaOfObject:object];
        [object addObserver:self forKeyPath:@"meta" options:0 context:NULL];
        [object addObserver:self forKeyPath:@"children" options:0 context:NULL];
        [object addObserver:self forKeyPath:@"childrenUpdated" options:0 context:NULL];
        [object addObserver:self forKeyPath:@"fetchDate" options:0 context:NULL];
        [object addObserver:self forKeyPath:@"error" options:0 context:NULL];
    }
    
    [self reloadLoginButton];
}

- (void)reloadData {
    GSSHome *home = (GSSHome *)object;
    
    self.footerTopLabel.text = [NSString stringWithFormat:
                                LocalizedString(@"{Bytes used}"),
                                [FormattingUtilities byteStringForSize:home.totalBytes],
                                home.totalFiles];
    self.footerBottomLabel.text = [NSString stringWithFormat:
                                   LocalizedString(@"{Bytes available}"),
                                   [FormattingUtilities byteStringForSize:home.bytesRemaining]];
    self.footerAnnouncementsLabel.text = [home.announcement stringByStrippingHTMLTags];
    
    if (self.isLoading) {
        // Don't show zero values if loading
        if (!home.totalBytes)
            self.footerTopLabel.text = nil;
        if (!home.bytesRemaining)
            self.footerBottomLabel.text = nil;
    }
    
    [self.tableView reloadData];
}

@end